home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 1486 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.9 KB  |  63 lines

  1. Path: news.th-darmstadt.de!news
  2. From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Deep/Shallow Copying?
  5. Date: Thu, 11 Jan 1996 10:31:09 +0100
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Message-ID: <30F4D8DD.167EB0E7@intellektik.informatik.th-darmstadt.de>
  8. References: <4d1bhe$1lto@bocanews.bocaraton.ibm.com>
  9. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0b4 (X11; I; SunOS 4.1.3 sun4m)
  14.  
  15. pani@genius.tisl.soft.net wrote:
  16. > Hi Guys,
  17. >       What is Deep copying or Shallow copying? Is this something
  18. > to do with a Copy constructor?
  19. > Thanks for any help.
  20. >
  21.  
  22. I'm not for sure if this expression is often used in _C++_. Anyway ...
  23. A shallow copy just copies the data-members of a class by memberwise
  24. copying each of them. Deep copying does some additional work, e.g. 
  25. replicating associated data. The easiest example that outlines the
  26. difference is a class that maintains a single pointer:
  27.  
  28.         struct A {
  29.             A() : a_(new char('a')) {}
  30.             ~A() { delete a_; }
  31.             char* a_;
  32.         };
  33.  
  34. The compiler-provided default copy-ctor does a shallow copy and so
  35. only the pointer-value not its related data is copied. Thus
  36.  
  37.         A a;                         A a,b
  38.         A b(a);          or          b=a;
  39.  
  40. will cause problems when 'a' and 'b' get destructed because they share
  41. the same 'char'-instance. To remove the problem one provides a suitable
  42. copy-ctor and assignment-op:
  43.  
  44.         struct A {
  45.             A() : a_(new char('a')) {}
  46.             A(const A& a) : a_(new char(*a.a_)) {}
  47.             A& operator = (const A& a) {
  48.               if (this!=&a) { delete a_; a_=new char(*a.a_); }
  49.               return *this;
  50.             }
  51.             ~A() { delete a_; }
  52.             char* a_;
  53.         };
  54.  
  55. Now a deep copy is created, ie. the related char-instance is also
  56. duplicated.
  57. So, you get the shallow-copy for free in C++, but a deep-copy needs
  58. mostly
  59. some additional code.
  60.  
  61.     Enno
  62.